<?php
namespace User\Controller;
use User\Controller\UserController;
use Think\Log;
use Think\Page;
use User\Common\GetErrorMsg;
class CustomMenuController extends UserController{

       public $thisWxUser;

       public function __construct() {
              parent::__construct();
              $where=array('token'=>$this->token);
             
              $this->thisWxUser=M('Wxuser')->where($where)->find();

              if (!$this->thisWxUser['appid']||!$this->thisWxUser['appsecret']){

                     $this->error('请先设置AppID和AppSecret再使用本功能，谢谢');

              }
       
       }

       //自定义菜单配置

       public function index(){
           $menuNode = M('custom_menu_node');
           $count = M('custom_menu_node')->where(array('token' => $this->token, 'pid' => 0, 'is_show' => 1))->order('sort asc')->count();

           $page = new Page($count, 3);
           $show = $page->show();
           $orderby['sort'] = 'desc';

           $list = $menuNode->where(array('token' => $this->token, 'pid' => 0, 'is_show' => 1))->limit($page->firstRow.','.$page->listRows)->select();

           foreach ($list as $key => $item) {
              $childNode = M('custom_menu_node')->where(array('token' => $this->token, 'pid' => $item['id'], 'is_show' => 1))->order('sort asc')->select();

              $list[$key]['childNode'] = $childNode;
           }
      
           $this->assign('list', $list);
           $this->assign('page', $show);
           $this->display();

       }

       public function  node_add(){

              if(IS_POST){

                     $menuNode = M('custom_menu_node');
                     $menuNode->token = $this->token;
                     $menuNode->title = $_POST['title'];
                     $menuNode->pid   = $_POST['pid'];
                     $menuNode->type  = $_POST['type'];
                     $menuNode->keyword = $_POST['keyword'];
                     $menuNode->url     = $_POST['url'];
                     $menuNode->sort    = $_POST['sort'];
                     $menuNode->is_show = 1;
                     $data = $menuNode->add();
                     if( $data )
                     {
                         $this->success('操作成功', '/User/CustomMenu/index');
                     }
                     else
                     {
                         $this->error('操作失败', '/User/CustomMenu/node_add/id/'.$data);
                     }

              }else{

                     $node=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>0))->order('sort asc')->select();
                     $this->assign('node',$node);
              
                     $this->display();
              }

       }

       public function  node_delete(){

              $node=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>$_GET['id']))->order('sort asc')->find();

              if($node==false){

                     $back=M('custom_menu_node')->where(array('token'=>session('token'),'id'=>$_GET['id']))->delete();

                     if($back==true){

                            $this->success('删除成功');

                     }else{

                            $this->error('删除失败');

                     }

              }else{

                     $this->error('请删除该分类下的子分类');

              }

       }

       public function  node_edit(){
               $data=M('custom_menu_node')->where(array('token'=>$this->token,'id'=>$_GET['id'], 'is_show'=>1))->find();
              if(IS_POST){
                     $node = M('custom_menu_node');
                     $_POST['id'] = $node->id;
                     $node->pid   = $_POST['pid'];
                     $node->title = $_POST['title'];
                     $node->type  = $_POST['type'];
                     $node->keyword = $_POST['keyword'];
                     $node->sort    = $_POST['sort'];
                     $node->url     = $this->checkUrl($_POST['url']);
                     
                     if($node->where(array('id' => $node->id))->save())
                     {
                          $this->success('操作成功', '/User/CustomMenu/index');
                     }
                     else
                     {
                         $this->error('操作失败', '/User/CustomMenu/node_edit/id/'.$_POST['id']);
                     }

              }else{

                    

                     if($data==false){

                            $this->error('您所操作的数据对象不存在！');

                     }else{

                            $node=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>0))->order('sort desc')->select();
                            
                            $this->assign('node',$node);

                            $this->assign('data',$data);

                     }

                     $this->display();

              }

       }

        private function unicode2utf8_2($str) { // 关于unicode编码转化的第二个函数，用于显示emoji表情

            $str = '{"result_str":"' . $str . '"}'; // 组合成json格式

            $strarray = json_decode ( $str, true ); // json转换为数组，利用 JSON 对 \uXXXX 的支持来把转义符恢复为 Unicode 字符（by 梁海）

            return $strarray['result_str'];

        }      

      

       public function  menu_send(){
              if(IS_GET){

                     $url_get='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->thisWxUser['appid'].'&secret='.$this->thisWxUser['appsecret'];

                     $json=json_decode($this->curlGet($url_get));

                     if (!$json->errmsg){

                            //return array('rt'=>true,'errorno'=>0);

                     }else {

                            $this->error('获取access_token发生错误：错误代码'.$json->errcode.',微信返回错误信息：'.$json->errmsg);

                     }

                     $data = '{"button":[';

                     $pNode=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>0,'is_show'=>1))->limit(3)->order('sort asc')->select();

                     $kcount=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>0,'is_show'=>1))->limit(3)->order('sort asc')->count();

                     $k=1;

                     foreach($pNode as $key=>$vo){

                            //主菜单

                         if ($vo['emoji_code'] != '') {

                                 $vo['title'] =  $this->unicode2utf8_2 ( '\u' . $vo['emoji_code']).$vo['title'];

                         }

                            $data.='{"name":"'.$vo['title'].'",';

                            $c=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>$vo['id'],'is_show'=>1))->limit(5)->order('sort desc')->select();

                            $count=M('custom_menu_node')->where(array('token'=>session('token'),'pid'=>$vo['id'],'is_show'=>1))->limit(5)->order('sort desc')->count();

                            //子菜单

                            $vo['url']=str_replace(array('{siteUrl}','&amp;','&wecha_id={wechat_id}'),array($this->siteUrl,'&','&customMenu=1'),$vo['url']);

                            if($c!=false){

                                   $data.='"sub_button":[';

                            }else{
                                   //无子菜单，设置一级菜单操作

                                   switch ($vo['type']) {
                                          case 'click':
                                                 $data.='"type":"'.$vo['type'].'","key":"'.$vo['keyword'].'"';
                                                 break;
                                          case 'view':
                                                 $data.='"type":"'.$vo['type'].'","url":"'.$vo['url'].'"';
                                                 break;
                                          default:
                                                 $data.='"type":"'.$vo['type'].'","key":"'.$vo['keyword'].'","sub_button":[]';
                                                 break;
                                   }
                                   

                            }
                           

                            $i=1;

                            foreach($c as $voo){

                                        if ($voo['emoji_code'] != '') {

                                            $voo['title'] =  $this->unicode2utf8_2 ( '\u' . $voo['emoji_code']).$voo['title'];

                                        }

                                   $voo['url']=str_replace(array('{siteUrl}','&amp;','&wecha_id={wechat_id}'),array($this->siteUrl,'&','&customMenu=1'),$voo['url']);

                                   if($i==$count){
                                          switch ($voo['type']) {
                                          case 'click':
                                                  $data.='{"type":"'.$voo['type'].'","name":"'.$voo['title'].'","key":"'.$voo['keyword'].'"}';
                                                 break;
                                          case 'view':
                                                 $data.='{"type":"'.$voo['type'].'","name":"'.$voo['title'].'","url":"'.$voo['url'].'"}';
                                                 break;
                                          default:
                                                  $data.='{"type":"'.$voo['type'].'","name":"'.$voo['title'].'","key":"'.$vo['keyword'].'","sub_button":[]}';
                                               
                                                 break;
                                          }

                                   }else{
                                          switch ($voo['type']) {
                                          case 'click':
                                                  $data.='{"type":"'.$voo['type'].'","name":"'.$voo['title'].'","key":"'.$voo['keyword'].'"},';
                                                 break;
                                          case 'view':
                                                 $data.='{"type":"'.$voo['type'].'","name":"'.$voo['title'].'","url":"'.$voo['url'].'"},';
                                                 break;
                                          default:
                                                  $data.='{"type":"'.$voo['type'].'","name":"'.$voo['title'].'","key":"'.$vo['keyword'].'","sub_button":[]},';
                                               
                                                 break;
                                          }

                                   }

                                   $i++;

                            }

                            if($c!=false){

                                   $data.=']';

                            }

 

                            if($k==$kcount){

                                   $data.='}';

                            }else{

                                   $data.='},';

                            }

                            $k++;

                     }

                     $data.=']}';
                     
 

                     file_get_contents('https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$json->access_token);

                     $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$json->access_token;

 

                     $rt=$this->api_notice_increment($url,$data);

 

                     if($rt['rt']==false){

                            $errmsg=GetErrorMsg::wx_error_msg($rt['errorno']);

                            $this->error('操作失败,'.$rt['errorno'].':'.$errmsg);

                     }else{

                            $this->success('操作成功');

                     }

                     exit;

              }else{

                     $this->error('非法操作');

              }

       }


      public function menu_delete()
      {
          if(IS_GET)
          {
              $url_get='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->thisWxUser['appid'].'&secret='.$this->thisWxUser['appsecret'];

             $json=json_decode($this->curlGet($url_get));

             if (!$json->errmsg){

                    //return array('rt'=>true,'errorno'=>0);

             }else {

                    $this->error('获取access_token发生错误：错误代码'.$json->errcode.',微信返回错误信息：'.$json->errmsg);

             } 
             
             $url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$json->access_token;

             $result = json_decode($this->curlGet($url));

             if(!$result->errcode)
             {
                 $this->success('停用自定义菜单成功', '/User/CustomMenu/index');
             }
             else
             {
                 $this->error('停用自定义菜单失败,错误代码'.$result->errcode.',微信返回错误信息：'.$result->errmsg);
             }

          }
      }       

       function api_notice_increment($url, $data){
              $ch = curl_init();

              $header = "Accept-Charset: utf-8";

              curl_setopt($ch, CURLOPT_URL, $url);

              curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

              curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);

              curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

              curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

              curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

              curl_setopt($ch, CURLOPT_AUTOREFERER, 1);

              curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

              $tmpInfo = curl_exec($ch);

              $errorno=curl_errno($ch);

              if ($errorno) {

                     return array('rt'=>false,'errorno'=>$errorno);

              }else{

                     $js=json_decode($tmpInfo,1);

                     if ($js['errcode']=='0'){

                            return array('rt'=>true,'errorno'=>0);

                     }else {

                            $errmsg=GetErrorMsg::wx_error_msg($js['errcode']);

                            $this->error('发生错误：错误代码'.$js['errcode'].',微信返回错误信息：'.$errmsg);

                     }

              }

       }

       function curlGet($url){
              $ch = curl_init();

              $header = "Accept-Charset: utf-8";

              curl_setopt($ch, CURLOPT_URL, $url);

              curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

              curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);

              curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

              curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

              curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

              curl_setopt($ch, CURLOPT_AUTOREFERER, 1);

              curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

              $temp = curl_exec($ch);

              return $temp;

       }

       protected function checkUrl($url)
       {

              if(strpos($url, "wecha_id") !== false){

                     if (strpos($url, "{wechat_id}") === false) {

                            $this->error('链接中设置的wecha_id ，不合法请从功能库选择链接');

                     }

              }

              return $url;

       }

}

       ?>